package com.cloud.template.base.util;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


/**
 * 发送邮件的工具类
 * 指定邮件服务器，密码，发送地址，发送内容等信息，就可以发送邮件了
 *
 */
public class EmailUtils {
	
	public static void sendEmail(Object content, String subject, String[] from, String[] to) throws MessagingException{
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
    	props.put("mail.smtp.timeout", "25000");
    	
    	String[] cc = {};
    	String[] bcc = {};
    	Date date = new Date();
		EmailUtils.send("smtp", "smtp.qiye.163.com", "发送者邮箱", "a123456", props, "", content, subject, from, to, cc,bcc,date);
	}
	/**
	 * 
	 * @param protocol 邮件协议，默认填入“smtp”
	 * @param host 邮件服务器
	 * @param username 如果需要认证（一般情况下必须），则为认证用户名
	 * @param password 同上，密码
	 * @param props 具体的发送参数,默认包含：
	    	props.put("mail.smtp.auth", "true");
	    	props.put("mail.smtp.timeout", "25000");
	 * @param contentType 邮件头的contentType定义，类似于HTML同一元素
	 * @param content 邮件内容
	 * @param subject 邮件标题
	 * @param from 发件人
	 * @param to 收件人
	 * @param cc 抄送
	 * @param bcc 密送
	 * @param sentDate 发送时间
	 * @throws MessagingException
	 */
	public static void send(String protocol, String host, String username,
                            String password, Properties props, String contentType,
                            Object content, String subject, String[] from, String[] to,
                            String[] cc, String[] bcc, Date sentDate) throws MessagingException {
		if (from == null || from.length < 1) {
			throw new IllegalArgumentException("no send from specified");
		}
		if (to == null || to.length < 1) {
			throw new IllegalArgumentException("no send to specified");
		}

		Session sendMailSession = Session.getInstance(props);
		Message message = new MimeMessage(sendMailSession);
		message.setSubject(subject);
		InternetAddress[] fromAddr = new InternetAddress[from.length];
		for (int i = 0; i < from.length; i++) {
			fromAddr[i] = new InternetAddress(from[i]);
		}
		message.addFrom(fromAddr);

		for (int i = 0; i < to.length; i++) {
			message.addRecipient(RecipientType.TO, new InternetAddress(to[i]));
		}
		if (cc != null && cc.length > 0) {
			for (int i = 0; i < to.length; i++) {
				message.addRecipient(RecipientType.CC, new InternetAddress(
						cc[i]));
			}
		}
		if (bcc != null && bcc.length > 0) {
			for (int i = 0; i < bcc.length; i++) {
				message.addRecipient(RecipientType.BCC, new InternetAddress(
						bcc[i]));
			}
		}
		message.setSentDate(sentDate);
		message.setContent(content, "text/html; charset=UTF-8");
		Transport transport = sendMailSession.getTransport(protocol);
		transport.connect(host, username, password);
		transport.sendMessage(message, message.getAllRecipients());
	}
	
	public static void send(String host, String username, String password, String[] from, String contentType, String content,
                            String subject, String[] to, String[] cc, String[] bcc, Date date,
                            Object[] args) throws MessagingException {
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.timeout", "25000");
		if(args!=null && args.length>0){
			content = MessageFormat.format(content, args);
		}
		if(from == null){
			from = new String[] { username };
		}
		send("smtp", host, username, password, props, contentType,content,
				subject, from, to, cc, bcc, date);
	}
	
	/**
	 * add by jun.yu 
	 * @title 通过邮件发送附件
	 * @param filePath 文件路径
	 * @param fileName 文件名
	 * @param to 收件人
	 * @param title 主题
	 * @param content 内容
	 * @throws EmailException
	 */
    public static void sendFile(String filePath, String fileName, String to, String title, String content) throws EmailException{
//      创建一个Email附件   
        EmailAttachment emailattachment = new EmailAttachment();   
        emailattachment.setPath(filePath);   
        emailattachment.setDisposition(EmailAttachment.ATTACHMENT);   
        emailattachment.setName(fileName);   
        
//      创建一个email   
        MultiPartEmail multipartemail = new MultiPartEmail();   
        multipartemail.setHostName("smtp.hkrt.com");   
        multipartemail.addTo(to);   
        multipartemail.setFrom("support@hkrt.com", "support");   
        multipartemail.setAuthentication("support@hkrt.com", "Z8j1c3");   
        multipartemail.setSubject(title);   
        multipartemail.setMsg(content);   
   
        //添加附件   
        multipartemail.attach(emailattachment);   
        //发送邮件   
        multipartemail.send();   
    }

	
	public static void send(String filePath, String attachName, String toAddress[], String toCcAddress[],
                            String fromAddress, String authUsername, String authPassword, String subject, String msg) throws EmailException
			
	{
	//	     创建一个Email附件   
		EmailAttachment emailattachment = new EmailAttachment(); 
		emailattachment.setPath(filePath);   
		emailattachment.setDisposition(EmailAttachment.ATTACHMENT);   
		try {
			emailattachment.setName("=?UTF-8?B?"+new String(new sun.misc.BASE64Encoder().encode(new String(attachName.getBytes()).getBytes("UTF-8")))+"?=");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//	     创建一个email   
		MultiPartEmail multipartemail = new MultiPartEmail();   
		multipartemail.setCharset("UTF-8");
		multipartemail.setHostName("smtp.hkrt.com");   
	    for(int i=0;i<toAddress.length;i++){  
			multipartemail.addTo(toAddress[i],toAddress[i]);  
	    } 
	    for(int j=0;j<toCcAddress.length;j++){
	    	multipartemail.addCc(toCcAddress[j], toCcAddress[j]);
	    }
		multipartemail.setFrom(fromAddress);   
		multipartemail.setAuthentication(authUsername, authPassword);   
		multipartemail.setSubject(subject);   
		multipartemail.setMsg(msg);
		//添加附件   
		multipartemail.attach(emailattachment);   
		//发送邮件   
		multipartemail.send();   
	}   
	
	public static void send(String filePath, String attachName, String toAddress, String toAddress2, String toCcAddress, String toCcAddress2, String fromAddress, String authUsername, String authPassword, String subject, String msg) throws EmailException{
		  
//	     创建一个Email附件   
	  
	       EmailAttachment emailattachment = new EmailAttachment();   
	  
	       emailattachment.setPath(filePath);   
	  
//	     emailattachment.setURL(new URL("http://www.blogjava.net/bulktree/picture/bulktree.jpg"));   
	  
	       emailattachment.setDisposition(EmailAttachment.ATTACHMENT);   
	  
//	       emailattachment.setDescription(attachDesc);   
	  
	       emailattachment.setName(attachName);   
	  
//	     创建一个email   
	  
	       MultiPartEmail multipartemail = new MultiPartEmail();   
	  
	       multipartemail.setHostName("smtp.hkrt.com");   
	  
	       multipartemail.addTo(toAddress);  
	       
	       multipartemail.addTo(toAddress2);
	       
	       multipartemail.addCc(toCcAddress);
	       
	       multipartemail.addCc(toCcAddress2);
	  
	       multipartemail.setFrom(fromAddress);   
	  
	       multipartemail.setAuthentication(authUsername, authPassword);   
	  
	       multipartemail.setSubject(subject);   
	  
	       multipartemail.setMsg(msg);   
	  
	       //添加附件   
	  
	       multipartemail.attach(emailattachment);   
	  
	       //发送邮件   
	  
	       multipartemail.send();   
	  
	}
	
	public static void sendEmail(String toAddress, String[] toCcAddress,
                                 String fromAddress, String authUsername, String authPassword, String subject, String msg) throws EmailException{
//	     创建一个email   
		MultiPartEmail multipartemail = new MultiPartEmail();   
		multipartemail.setHostName("smtp.hkrt.com");   
		multipartemail.addTo(toAddress); 
		for(int i=0;i<toCcAddress.length;i++){
			multipartemail.addCc(toCcAddress[i]);
		}	
//	    multipartemail.addCc(toCcAddress);
		multipartemail.setFrom(fromAddress);   
		multipartemail.setAuthentication(authUsername, authPassword);   
		multipartemail.setSubject(subject);   
		multipartemail.setMsg(msg);   
		//发送邮件   
		multipartemail.send();
	}
	
	public static void sendmail(String toAddress, String toCcAddress,
                                String fromAddress, String authUsername, String authPassword, String subject, String msg) throws EmailException
	{
		//	     创建一个email   
		MultiPartEmail multipartemail = new MultiPartEmail();   
		multipartemail.setHostName("smtp.hkrt.com");   
		multipartemail.addTo(toAddress); 
		if(!toCcAddress.equals(""))
	    multipartemail.addCc(toCcAddress);
		multipartemail.setFrom(fromAddress);   
		multipartemail.setAuthentication(authUsername, authPassword);   
		multipartemail.setSubject(subject);   
		multipartemail.setMsg(msg);   
		//发送邮件   
		multipartemail.send();   
	}
	
	public static void sendmail(String[] toAddress, String[] toCcAddress, String hostName, String fromAddress, String authUsername, String authPassword, String subject, String msg) throws EmailException
	{
		//	     创建一个email   
		MultiPartEmail multipartemail = new MultiPartEmail();   
		multipartemail.setHostName(hostName); 
		if(toAddress!=null && toAddress.length>0){
			for(int i=0;i<toAddress.length;i++){
				multipartemail.addTo(toAddress[i]);
			}
		}else{
			return ;
		}
		if(toCcAddress!=null && toCcAddress.length>0){
			for(int i=0;i<toCcAddress.length;i++){
				multipartemail.addCc(toCcAddress[i]);
			}
		}
		multipartemail.setFrom(fromAddress);   
		multipartemail.setAuthentication(authUsername, authPassword);   
		multipartemail.setSubject(subject);   
		multipartemail.setMsg(msg);   
		//发送邮件   
		multipartemail.send();   
	}
	
	public static void sendmail(String[] toAddress, String[] toCcAddress, String hostName, String fromAddress, String authUsername, String authPassword, String subject, String msg, String attachName, String filePath) throws EmailException
	{
		//	     创建一个email   
		MultiPartEmail multipartemail = new MultiPartEmail();   
		multipartemail.setHostName(hostName); 
		if(toAddress!=null && toAddress.length>0){
			for(int i=0;i<toAddress.length;i++){
				multipartemail.addTo(toAddress[i]);
			}
		}else{
			return ;
		}
		if(toCcAddress!=null && toCcAddress.length>0){
			for(int i=0;i<toCcAddress.length;i++){
				multipartemail.addCc(toCcAddress[i]);
			}
		}
		multipartemail.setFrom(fromAddress);   
		multipartemail.setAuthentication(authUsername, authPassword);   
		multipartemail.setSubject(subject);   
		multipartemail.setMsg(msg);
		if(attachName!=null && filePath!=null){
			File target = new File(filePath);
			if (target.exists()) {
					//创建一个Email附件   
			       EmailAttachment emailattachment = new EmailAttachment();   
			       emailattachment.setPath(filePath);   
			       emailattachment.setDisposition(EmailAttachment.ATTACHMENT);   
			       emailattachment.setName(attachName);   
			       multipartemail.attach(emailattachment); 
			}
		}
		//发送邮件   
		multipartemail.send();   
	}
	
	public static void sendEmail(Object content, String subject, String[] to) throws MessagingException{
		PropertyUtil manager = PropertyUtil.getInstance(Constant.PROPERTIES_SYS);
		String protocol = manager.getProperty("email.protocol");
		String host = manager.getProperty("email.host");
		String sender=null;
		SimpleDateFormat formatter = new SimpleDateFormat("HH");
		String nowTime = formatter.format(new Date());
		if(Integer.parseInt(nowTime)%2==1){
			sender=manager.getProperty("email.sender1");
		}else{
			sender=manager.getProperty("email.sender2");
		}
		String password = manager.getProperty("email.sender.passcode");
		
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
    	props.put("mail.smtp.timeout", "25000");
    	String[] from = { sender };
    	String[] cc = {};
    	String[] bcc = {sender};
    	Date date = new Date();
		EmailUtils.send(protocol, host, sender, password, props, "", content, subject, from, to, cc,bcc,date);
	}
	
	
}
